 <!--
  -    Copyright (c) 2018-2025, gewu All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the gewucn.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: gewu
  -->
<template>
  <!-- <el-dialog title="点检项目管理" :visible.sync="dialoged" width="80%"> -->
  <div class="dialigexecution">
    <el-card class="box-card btn-search page-search">
      <div slot="header" class="clearfix">
        <div class="btn-box">
          <el-button
            type="info"
            icon="el-icon-refresh-left"
            @click="refreshChange()"
          ></el-button>
          <el-button
            id="gwButton"
            type="primary"
            style="backgroundcolor: #e1b980"
            icon="el-icon-circle-plus-outline"
            v-if="permissions.ems_emsinsinspectitems_add"
            @click="addSub"
            >新增</el-button
          >
          <el-button
            type="success"
            icon="el-icon-edit"
            v-if="permissions.ems_emsinsinspectitems_edit"
            :disabled="single"
            @click="handleEdit"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-circle-close"
            v-if="permissions.ems_emsinsinspectitems_del"
            @click.native="handleDel()"
            :disabled="multiple"
            >删除</el-button
          >
          <el-button type="check" icon="el-icon-download" @click="exportExcel"
            >导出</el-button
          >
        </div>
        <div class="icon-box">
          <i class="el-icon-search" @click="searchShow"></i>
          <i class="el-icon-refresh" @click="refreshChange"></i>
          <i class="el-icon-goods"></i>
          <i class="el-icon-setting" @click="columnShow"></i>
          <i class="icon-zuixiaohua" />
        </div>
      </div>
    </el-card>
    <basic-container>
      <div class="icon-title">
        <img src="/img/ali/yunwei.png" alt />
        <b>巡检项目 </b>
      </div>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @selection-change="selectionChange"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="handleDel"
      >
      
       <!-- <template slot="header">
          <IconTitle class="selfTitle" title="巡检项目" imgUrl="yunwei" />
        </template> -->
      </avue-crud>
      
    </basic-container>
    <el-dialog
  :title="titleD"
  :visible.sync="isdialogVisible"
  width="40%"
  :modal="false"
  :show-close="false"
  >
  <el-form ref="form" :model="form"  :rules="rules" label-width="100px">
    <el-form-item label="项目" prop="itemsName">
     <el-input v-model="form.itemsName" ></el-input>
  </el-form-item>
  <el-form-item label="方法及基准" prop="methodBenchmark">
     <el-input v-model="form.methodBenchmark"></el-input>
  </el-form-item>
  <el-form-item label="类型" prop="type">
    <el-select v-model="form.type" style="width:100%;">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
    </el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="范围" v-if="form.type==1">
    <el-input v-model="form.lowerLimit" style="width:45%"></el-input>
    ~
    <el-input v-model="form.upperLimit" style="width:45%"></el-input>
  </el-form-item>
  <el-form-item label="选项" v-if="form.type==2" class="appendAfter">
    <i class="el-icon-circle-plus-outline" @click="addInput"></i>
    <template v-for="item,index in itemList" >
     <el-input v-model="item.optional" :key="index" style="margin:5px 0;">
        <template slot="append" >
          <div @click="removeInput(index)">-</div></template>
     </el-input>
    </template>
  </el-form-item>
  <el-form-item label="正确值" v-if="form.type!=1">
      <el-input v-model="form.normalOption"></el-input>
  </el-form-item>
  <el-form-item label="备注" >
      <el-input  type="textarea" :rows="2" v-model="form.remark"></el-input>
  </el-form-item>
  <el-form-item label="图片" >
  <el-upload
          ref="upload"
            class="upload-demo"
            action="/admin/sys-file/upload"
            name="file"
            :headers="headers"
            multiple
            :on-success="handleAvatarSuccess"
            :file-list="fileList"
             :auto-upload="true"
              :on-change="handleFileChange"
              :before-remove="handleFileRemove"
          >
           <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          </el-form-item>
  </el-form>
  <div slot="footer" style="text-align:center" >
    <el-button @click="isdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleSave" v-if="titleD=='新增'">确 定</el-button>
    <el-button type="primary" @click="handleUpdate" v-if="titleD=='修改'">确 定</el-button>
  
  </div>
</el-dialog>
  </div>
  <!-- </el-dialog> -->
</template>
<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  uploadFile,
  selectList
} from "@/api/ems/inspection/spoted";
import { tableOption } from "@/const/crud/ems/inspection/spoted";
import { mapGetters } from "vuex";
import jQuery from "jquery";
import IconTitle from "@/components/icon-title/index.vue";
import store from "@/store";
export default {
  name: "emsinsinspectitems",
  components: {
    IconTitle,
  },
  props: {
    params: Object,
    dialogspotVisible: Boolean,
  },
  data() {
    return {
      tableData: [],
      searchForm: {}, // 查询参数
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      ids: [],
      imgArray:[],
      selectionList: [],
      dialoged: this.dialogspotVisible,
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
       
      },
      fileList:[],
      fileName:[],
      form:{
        itemsName:'',
        methodBenchmark:'',
        type:'',
        lowerLimit:'',
        upperLimit:'',
        optional:'',
        normalOption:'',
        remark:''
      },
      options:[],
      isdialogVisible:false,
      titleD:'新增',
      itemList:[
        {
          optional:""
        }
      ],
      rules:{
         itemsName: [
            { required: true, message: '请输入项目', trigger: 'blur' }
          ],
          methodBenchmark:[
            { required: true, message: '请输入方法及基准', trigger: 'blur' }
          ],
          type:[
            { required: true, message: '请选择类型', trigger: 'change' }
          ]
      }
    };
  },
  computed: {
    ...mapGetters(["permissions", "theme"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.ems_emsinsinspectitems_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.ems_emsinsinspectitems_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.ems_emsinsinspectitems_edit,
          false
        ),
      };
    },
    // achieve:{
    //     get(){
    //         return this.dialoged
    //     },
    //     set(){
    //         this.dialoged = !this.dialoged
    //     }
    // }
    // dialogspot:{
    //     get(){
    //         this.dialoged = this.dialogspotVisible;
    //         return this.dialogspotVisible;
    //     },
    //     set(){
    //         this.dialoged = this.dialogspotVisible;
    //     }
    // }
  },
  watch:{
      'form.type':{
        handler: function() {
            //do something
            if(this.form.type==0){
              this.form.lowerLimit="";
              this.form.upperLimit="";
              this.itemList=[{}]
            }else if(this.form.type==1){
              this.form.normalOption="";
              this.itemList=[{}]
            }else{
              this.form.lowerLimit="";
              this.form.upperLimit="";
            }
           
         },
      }
  },
  mounted() {
    // console,log(this.dialogspotVisible)
    // this.dialoged = this.dialogspotVisible;
    //this.initElement();
    this.changeThme();
    this.getSelectList();
  },
  methods: {
    addInput(){
      this.itemList.push({optional:""})
      
    },
    removeInput(index){
      console.log(index)
      this.itemList.splice(index,1)
    },
    getSelectList(){
      selectList().then((res)=>{
        this.options = res.data.data;
        this.form.type = this.options[0].value
      })
    },
    handleAvatarSuccess(response, file, fileList) {
      
    this.fileList = fileList;
    },
    achiveFileList(){
         let arr = []
      this.fileList.map((item)=>{

          if(item.response){
              let id = item.response.data.fileId
              let newId = parseInt(id)
          arr.push(id);
          }
          this.imgArray = [...new Set(arr)]
         
          
      })
    },
    handleFileChange(file, fileList) {
        
		this.fileList = fileList;
       
		},
        handleFileRemove(file, fileList) {
      this.fileList = fileList;
      
    },
    initElement() {
      var mediumb = document.createElement("b"); //思路一样引入中间元素
      jQuery(".avue-crud__menu").after(mediumb);
      jQuery(".selfTitle").after(jQuery(".avue-crud__menu"));
      jQuery(mediumb).after(jQuery(".selfTitle"));
      jQuery(mediumb).remove();
    },
    selectionChange(list) {
      this.selectionList = list;
      this.single = list.length !== 1;
      this.multiple = !list.length;
      this.ids = list.map((item) => item.id);
    },

    columnShow() {
      this.$refs.crud.$refs.dialogColumn.columnBox = !0;
    },
    // 搜索框显示与否
    searchShow() {
      this.$refs.crud.$refs.headerSearch.searchShow =
        !this.$refs.crud.$refs.headerSearch.searchShow;
    },

    // 列表查询
    getList(page, params) {
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          params,
          this.searchForm,
          { standardId: this.params.id }
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    //编辑
    handleEdit() {
      this.titleD = "修改";
      this.isdialogVisible=true;

       let refsDate = this.$refs.crud;
       let index = this.selectionList[0].$index
     // this.form.optional="";
      //  refsDate.map((item)=>{
      //    this.form[item]
      //  })
      let arr = this.selectionList[0].optional.split(",")
      let newArr=[]
      arr.map((item,index)=>{
        
        newArr.push({optional:item})
      })
      this.itemList = newArr;
      console.log(this.itemList);
      console.log(this.form.optional)
    this.form =this.selectionList[0];
       
      // refsDate.crud.rowEdit(
      //   this.selectionList[0],
      //   this.selectionList[0].$index
      // );
    },
    // 删除
    handleDel: function (row, index) {
      this.$confirm("是否确认删除所选数据项", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let id = "";
          if (row) {
            id = row.id;
          } else {
            id = this.ids;
          }
          return delObj(id);
        })
        .then((data) => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    // 更新
    handleUpdate: function (row, index, done, loading) {
       this.form.optional=""
       this.itemList.map((item,index)=>{
      if(item!=""){
       
        if(index<this.itemList.length-1){
          this.form.optional+=item.optional+","
        }else{
           this.form.optional+=item.optional
        }
        
      }
    })
    
        this.achiveFileList();
      putObj({ standardId: this.params.id, ...this.form,imgIdArray: this.imgArray })
        .then((data) => {
          this.$message.success("修改成功");
          this.isdialogVisible=false;
          this.getList(this.page);
           this.$refs.upload.clearFiles()
            // done();
        })
        .catch(() => {
          // loading();
        });
    },
    addSub(){
       this.titleD = "新增";
      this.isdialogVisible=true;
      this.form.itemsName="";
      this.form.methodBenchmark="";
      this.form.type="0";
      this.form.lowerLimit="";
      this.form.upperLimit="";
      this.form.optional="";
      this.form.normalOption="";
      this.form.remark="";
    this.itemList=[{}];
      
    },
    // 保存
    handleSave: function (row, done, loading) {
        this.$refs.form.validate((valid) => {
       
          if (valid) {
               
       
    this.itemList.map((item,index)=>{
      if(item!=""){
       
        if(index<this.itemList.length-1){
          this.form.optional+=item.optional+","
        }else{
           this.form.optional+=item.optional
        }
        
      }
    })
    
   
       this.$refs.upload.submit();
       this.achiveFileList()
      addObj({ standardId: this.params.id, ...this.form ,imgIdArray: this.imgArray})
        .then((data) => {
          this.$message.success("添加成功");
         
          this.getList(this.page);
          this.$refs.upload.clearFiles();
          this.fileList = [];
          this.imgArray = [];
          
          this.isdialogVisible=false;
          //  done();
        })
        .catch(() => {
          // loading();
        });
        } else {
           
      return
          }
        });
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current;
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page);
    },
    // 导出excel
    exportExcel() {
      this.downBlobFile(
        "/ems/emsinsinspectitems/export",
        this.searchForm,
        "emsinsinspectitems.xlsx"
      );
    },
    // 改变主题颜色
    changeThme() {
      //"#02b980"
      document.getElementById("gwButton").style.backgroundColor = this.theme;
    },
  },
};
</script>
<style lang="scss" scoped>
.icon-title {
  b {
    font-size: 12px;
  }
  .slot {
    font-size: 12px;
    color: #666;
    margin-left: 5px;
  }
  img {
    width: 18px;
    height: 18px;
  }
  display: flex;
  align-items: center;
}
::v-deep .basic-container {
  .el-card__body {
    padding-top: 0 !important;
  }
 
}
::v-deep .appendAfter{
 .el-input-group__append{
    background-color: #02b980;
    border:1px solid #02b980;
    color: white;
    font-size: 20px;
    cursor: pointer;
  }
}
</style>